<?php
namespace app\common\behavior;
use app\common\model as M;

/**
 * 完成一笔订单成功后回调
 * 01 检查签到配置中是否有登录送金币活动
 */
class OrderSuccess
{
    public function run(&$params)
    {
        if ( empty($params['uid']) ) return;

        M\User::startTrans();
        try {
            ## 01 检查签到任务中是否有消费订单类活动
            $orderTasks = M\SignTask::where('type',M\SignTask::TYPE_ORDER)->select();
            if ( !empty($orderTasks) ) {
                foreach ( $orderTasks as $orderTask ) {
                    $complete = M\SignTaskRecords::where(['task_id' => $orderTask->id,'uid' => $params['uid']])->count();
                    if ( $complete > 0 ) continue;

                    $res = M\SignTaskRecords::create([
                        'task_id'      => $orderTask->id,
                        'uid'          => $params['uid'],
                        'complete_date'=> date('Y-m-d H:i:s')
                    ]);
                    if ( $res === false ) throw new \Exception('Error 10091');

                    $res = M\user\UserGoldsBill::add($amt = $orderTask->golds , $stype = M\user\UserGoldsBill::STYPE_BUY  , $params['uid']);
                    if ( $res === false ) throw new \Exception('Error 10092');
                }

                M\User::commitTrans();
            }
        } catch (\Exception $e) {
            M\User::rollbackTrans();
            throw new \Exception($e->getMessage());
        }
    }
}